define(function(require, exports, module) {
    'use strict';

    var rk_userService = require('core/services/2.0/rk_userService');

    // require('globaljs');
    var rk = require('rk');
    require('../plus/tipApi');
    require('../controllers/calEventTypeSelCtrl');

    var scheduleUtil = require('oa/js/schedule/asset/utils/scheduleUtil');

    $.widget("rk.scheduleEditController", {
        options: {
            act: '', //create, edit, tip
            disabled: false,
            endDate: null,
            endTime: null,
            startDate: null,
            startTime: null,
            viewName: "month", //agendaDay, agendaWeek, month
            eventId: '',
            closeMe: null,
            planFinishDate: '',
            eventType: '', //task, schedule
            scheduleSucc: $.noop, //new
            scheduleFail: $.noop, //new
            taskSucc: $.noop, //new
            taskFail: $.noop //new
        },
        _create: function() {
            var $this = this,
                $elem = this.element,
                opt = this.options;
            var $named = $elem.find('[name]');
            $this.$scheduletype = $elem.find('div.js-color-type');
            $this.$startDate = $named.filter('[name="startDate"]');
            $this.$startTime = $named.filter('[name="startTime"]');
            $this.$endDate = $named.filter('[name="endDate"]');
            $this.$endTime = $named.filter('[name="endTime"]');
            $this.$allday = $named.filter('[name="isAllDay"]');
            $this.$repeat = $named.filter('[name="isRecur"]');
            $this.$repeatpanel = $elem.find('div.js-schedule-repeatpanel');
            $this.$repeattype = $named.filter('[name="frequency"]');
            $this.$repeattypepanel = $elem.find('div.js-schedule-repeatcond');
            $this.$stoptype = $named.filter('[name="recurStopCondition"]');
            $this.$stopcond = $named.filter('[name="recurStopValue"]');
            $this.$reminder = $named.filter('[name="reminder"]');
            $this.$opts_1 = $this.$reminder.find('option[isallday="1"]').remove();
            $this.$opts_0 = $this.$reminder.find('option[isallday="0"]').remove();

            $this.$player = $named.filter('[name="members"]');
            $this.$relation = $named.filter('[name="belongId"]');
            $this.$entry = $named.filter('[name="objectId"]');
            $this.$more = $elem.find('a.js-schedule-more');
            $this.$upload = $named.filter('[name="uploadfiles"]');
            $this.$queue = $elem.find('div.uploadifyQueue').uniqueId().show().width(380);
            $this.$rptinfo = $elem.find('span.js-rpt-info');
            $this.$tooltip = $elem.find('a.js-tooltip');

            $this.$btnClose = $elem.find('a.js-close');
            $this.$btnCreate = $elem.find('a.js-create');

            $this.initUI();
            $elem.scheduleformbean();
            $this.initValue();
        },
        initUI: function() {
            var $this = this,
                $elem = this.element,
                opt = this.options;
            var effect;

            $this.$allday.button();
            $this.$repeat.button();

            $this.$scheduletype.calEventTypeSelCtrl();
            $this.$startDate.add($this.$endDate).datepicker({
                showOtherMonths: true,
                selectOtherMonths: true
            });
            $this.$startEndTime = $this.$startTime.add($this.$endTime).timepicker({
                minutes: {
                    starts: 0, // first displayed minute
                    ends: 30, // last displayed minute
                    interval: 30 // interval of displayed minutes
                }
            });
            $this.$tooltip.tooltip({
                tooltipClass: 'qtip-dark-rk'
            });
            $this.$stopcond.datepicker({
                showOtherMonths: true,
                selectOtherMonths: true,
                onSelect: function(strDate, inst) {
                    $this._changeRepeatInfo();
                }
            });

            $this.$allday.on('click', function(evt) {
                if (this.checked) {
                    $this.$startEndTime.hide(effect);
                    $this.$opts_0.remove();
                    $this.$reminder.append($this.$opts_1);
                } else {
                    $this.$startEndTime.show(effect);
                    if (!$this.$startTime.val() && !$this.$endTime.val()) {
                        var start = moment();
                        start.set('minutes', 0);
                        start.set('second', 0);
                        start.add(60, 'minutes');
                        var end = moment(+start.toDate() + 30 * 60 * 1000);
                        $this.$startTime.val(start.format('HH:mm'));
                        $this.$endTime.val(end.format('HH:mm'));
                    }
                    $this.$opts_1.remove();
                    $this.$reminder.append($this.$opts_0);
                }
            }).triggerHandler('click');

            $this.$repeat.on('click', function(evt) {
                if (this.checked) {
                    $this.$repeatpanel.show(effect);
                    $this.$repeattype.triggerHandler('change');
                } else {
                    $this.$repeatpanel.hide(effect);
                }
                $this._changeRepeatInfo();
            });

            $this.$repeattype.selectmenu().on('selectmenuchange', function(evt, ui) {
                var value = ui ? ui.item.value : this.value;
                if (value == '0') {
                    $this.$repeattypepanel.is(':visible') && $this.$repeattypepanel.hide(effect);
                } else {
                    $this.$repeattypepanel.is(':hidden') && $this.$repeattypepanel.show(effect);
                }
                $this._changeRepeatInfo();
            });

            $this.$stoptype.selectmenu().on('selectmenuchange', function(evt, ui) {
                var value = ui ? ui.item.value : this.value;
                if (value == '1') {
                    $this.$stopcond.is(':visible') && $this.$stopcond.hide(effect);
                } else {
                    $this.$stopcond.is(':hidden') && $this.$stopcond.show(effect);
                }
                $this._changeRepeatInfo();
            });

            $this.$player.snsmultipeopleselector({
                position: {
                    my: 'left top+2'
                }
            });

            $this.$entry.autocomplete({
                source: $.noop,
                minLength: 1,
                select: function(event, ui) {
                    var item = ui.item;
                    $this.$entry.val(item.label);
                    $this.$entry.attr('objectId', item.value);
                    return false;
                },
                focus: function(event, ui) {
                    var item = ui.item;
                    $this.$entry.val(item.label);
                    $this.$entry.attr('objectId', item.value);
                    return false;
                }
            });
            $this.$relation.on('change', function(evt) {
                var $option = $('option:selected', this),
                    url = $option.attr('url');
                $this.$entry.autocomplete('option', 'source', url);
                evt.isTrigger || $this.$entry.val('').trigger('focus');
            }).triggerHandler('change');

            $this.$more.on('click', function(evt) {
                evt.preventDefault();
                $(this).parent().hide().nextAll().show(effect).find(':input').trigger('focus');
                $.setPopupLayersPosition();
            });

            if (opt.eventId) {
                $this.$btnCreate.text(rk.i18n('SAVE'));
                $elem.find('.fileinput-box').hide();
                $this.$more.triggerHandler('click');
            } else {
                /*var fileRecorder;
                $this.$upload.uniqueId().uploadSingleFile({
                    uploader: '/json/global_uploadify/task-create-upload.action',
                    queueID: $this.$queue.attr('id'),
                    buttonClass: 'file_select', // A class name to add to the browse button DOM object
                    buttonCursor: 'hand', // The cursor to use with the browse button
                    removeCompleted: false,
                    removeTimeout: 0,
                    buttonText: rk.i18n('APPS_FILE_ADD_FILE'),
                    fileTypeDesc: rk.i18n('APPS_FILE_ALL_FILE'),
                    fileTypeExts: '*.*',
                    fileSizeLimit: '80MB',
                    uploadLimit: 10,
                    fileObjName: 'uploadFile',
                    formData: {
                        pageTenantId: SESSION.tenantId
                    },
                    onSelect: function(file) {
                        if (fileRecorder) {
                            delete $this.$upload.data('uploadify').queueData.files[fileRecorder.id];
                            $this.$upload.uploadify("cancel", [fileRecorder.id], true);
                            //$("#" + fileRecorder.id).remove();
                        }
                    },
                    onCancel: function(file) {
                        fileRecorder = null;
                    },
                    onUploadStart: function(file) {},
                    onUploadSuccess: function(file, data, response) {
                        data = $.parseJSON(data);
                        if (data.status == 0) {
                            fileRecorder = $.extend(data, file);
                        } else {
                            delete $this.$upload.data('uploadify').queueData.files[fileRecorder.id];
                            $this.$upload.uploadify("cancel", [fileRecorder.id], true);
                            fileRecorder = null;
                        }
                    },
                    onDialogClose: function(queueData) {}
                });*/
                $elem.find('.fileinput-box').multifileuploader({
                    url: '/json/global_uploadify/task-create-upload.action',
                    itemSuccess: function() {
                        $elem.find('div.schedule_pop_content').css('height', 430).beScroll({
                            theme: 'dark'
                        });
                        $elem.find('div.schedule_pop_content').beScrollTo('bottom');
                    }
                });
            }

            $this.$btnClose.on('click', function(evt) {
                evt.preventDefault();
                rk.closePopup();
            });

            $this.$btnCreate.on('click', function(evt) {
                evt.preventDefault();
                var formdata = $elem.scheduleformbean('getAll'),
                    scheduletype = $this.$scheduletype.calEventTypeSelCtrl('getTypeId');
                if (!formdata.name) {
                    return $.msg(rk.i18n('SCHEDULE_4'));
                }
                if (formdata.name.length > 30) {
                    return $.msg(rk.i18n('SCHEDULE_5'));
                }
                if (!formdata.startDate || !formdata.endDate || (!formdata.isAllDay && (!formdata.startTime || !formdata.endTime))) {
                    return $.msg(rk.i18n('SCHEDULE_6'));
                }
                if (formdata.isAllDay && +formdata.endDate < +formdata.startDate || !formdata.isAllDay && (+formdata.endDate + ' ' + formdata.endTime <= +formdata.startDate + ' ' + formdata.startTime)) {
                    return $.msg(rk.i18n('SCHEDULE_7'));
                }
                if (formdata.isRecur && formdata.recurStopCondition == '2') {
                    if (!formdata.recurStopValue) {
                        return $.msg(rk.i18n('SCHEDULE_8'));
                    }
                    if (+formdata.recurStopValue < +formdata.endDate) {
                        return $.msg(rk.i18n('SCHEDULE_9'));
                    }
                }
                if (!formdata.members || !formdata.members.length) {
                    return $.msg(rk.i18n('SCHEDULE_10'));
                }

                if (formdata.objectId == undefined) {
                    formdata.objectId = $elem.find("input[name=objectId]").attr("value");
                }

                if (opt.sourceEntity) {
                    formdata.objectId = opt.sourceEntity.id;
                    formdata.belongId = opt.entityId;
                }

                var postdata = {
                    'paramMap.name': formdata.name,
                    'paramMap.type': scheduletype,
                    'paramMap.startDate': $.datepicker.formatDate('yy-mm-dd', formdata.startDate) + (!formdata.isAllDay ? ' ' + (formdata.startTime || '00:00') : ''),
                    'paramMap.endDate': $.datepicker.formatDate('yy-mm-dd', formdata.endDate) + (!formdata.isAllDay ? ' ' + (formdata.endTime || '00:00') : ''),
                    'paramMap.isAllDay': +formdata.isAllDay,
                    'paramMap.isRecur': +formdata.isRecur,
                    'paramMap.frequency': formdata.frequency,
                    'paramMap.interval': '1',
                    'paramMap.belongId': formdata.belongId,
                    'paramMap.objectId': formdata.objectId ? (formdata.objectId.value || formdata.objectId) : '',
                    //'paramMap.objectId': formdata.objectId ? formdata.objectId.value : '',
                    'paramMap.isPrivate': +formdata.isPrivate,
                    'paramMap.description': formdata.description,
                    'paramMap.recurStopCondition': formdata.recurStopCondition,
                    'paramMap.recurStopValue': $.datepicker.formatDate('yy-mm-dd', formdata.recurStopValue),
                    'reminder': formdata.reminder,
                    'members': formdata.members ? formdata.members.join(',') : ''
                };
                if (opt.eventId) {
                    postdata['paramMap.id'] = formdata.id;
                } else {
                    var $upload = $elem.find('.fileinput-box');
                    if ($upload.multifileuploader('status').uploading) {
                        return $.msg(rk.i18n('文件上传中...'));
                    }
                    var files = $upload.multifileuploader('val');
                    // var files = $elem.find('.fileinput-box').multifileuploader('val');

                    // if (!files.length) {
                    //     return $.msg(rk.i18n('APPS_FILE_CHOOSE_FILE_UPLOAD'));
                    // }

                    // var fileUploaded = true;
                    // $.each(files, function(k, v) {
                    //     if (!v.fileUrl || v.fileUrl == '') {
                    //         fileUploaded = false;
                    //     }
                    // });
                    // if (!fileUploaded) {
                    //     return $.msg(rk.i18n('文件上传中...'));
                    // }
                    postdata['attachments'] = JSON.stringify(files);
                    //postdata['attachments'] = fileRecorder ? JSON.stringify(fileRecorder) : '';
                }
                var $lnk = $(this).loading(),
                    behavior = opt.eventId ? rk.i18n('SCHEDULE_11') : rk.i18n('SCHEDULE_12');

                //if (!opt.eventId) {
                //    if(window._hmt){_hmt.push(['_trackEvent', 'operate', 'schedule_add', window.SESSION.tenantName]);}
                //}

                $.post('/json/crm_schedule/' + (opt.eventId ? 'update' : 'create') + '.action', postdata, null, 'json').done(function(json) {
                    if (json.status == '0') {
                        $.msg(behavior + rk.i18n('SCHEDULE_22'), 1);
                        rk.closePopup();
                        $this._delay(function() {
                            try {
                                opt.scheduleSucc(json);
                            } catch (ex) {
                                //location.reload();
                            }
                        }, 1000);
                    } else {
                        $.msg(behavior + rk.i18n('SCHEDULE_23'));
                        opt.scheduleFail();
                        $lnk.loading('end');
                    }
                }).fail(function(def, code, message) {
                    def.status != 0 && $.msg(rk.i18n('REQUEST_ERROR'));
                    $lnk.loading('end');
                });
            });

        },
        initValue: function() {
            var $this = this,
                $elem = this.element,
                opt = this.options;
            if (opt.eventId) {
                $elem.hide();
                var $loading = $('<div class="cal-loading"><span>' + rk.i18n('LOADING') + '…</span></div>').insertAfter($elem);
                $.getJSON('/json/crm_schedule/detail.action?scheduleId=' + opt.eventId, function(json) {
                    rk_userService.appendUserInfo(json.data.users);
                    $loading.remove();
                    $elem.show();
                    $this._initValue(json.data);
                });
            } else {
                var isAllDay = opt.isAllDay,
                    data = {
                        "schedule": {
                            "id": "",
                            "name": "",
                            "description": "",
                            "startDate": +new Date(opt.startDate.split('-').join('/') + (!isAllDay ? ' ' + opt.startTime : '')),
                            "endDate": +new Date(opt.endDate.split('-').join('/') + (!isAllDay ? ' ' + opt.endTime : '')),
                            "isAllDay": isAllDay ? '1' : '0',
                            "isRecur": '0',
                            "reminder": -1
                        },
                        "waitingMember": [SESSION.user.id].concat(opt.userId && SESSION.user.id != opt.userId ? [opt.userId] : []),
                        "rejectMember": [],
                        "acceptMember": [],
                        "users": (function(o) {
                            var obj = {};
                            obj[SESSION.user.id] = $.extend({}, o);
                            if (opt.userId && SESSION.user.id != opt.userId) {
                                obj[opt.userId] = {
                                    id: opt.userId,
                                    name: opt.userName
                                };
                            }
                            return obj;
                        })(window.SESSION.user)
                    };
                $this._initValue(data);
            }
        },
        _initValue: function(data) {
            var $this = this,
                $elem = this.element,
                opt = this.options;
            data = $.extend(true, data, data.schedule);
            delete data.schedule;

            if (data.colorType) {
                $this.$scheduletype.calEventTypeSelCtrl('setTypeId', data.colorType.id);
            }

            data.isAllDay = data.isAllDay == '1';
            data.isRecur = data.isRecur == '1';
            data.isPrivate = data.isPrivate == '1';

            if (data.startDate) {
                data.startDate = new Date(Number(data.startDate));
            }
            if (data.endDate) {
                data.endDate = new Date(Number(data.endDate));
            }

            if (data.recurStopValue && data.recurStopValue != '0') {
                data.recurStopValue = new Date(Number(data.recurStopValue));
            }

            if (!data.isAllDay) {
                if (data.startDate) {
                    data.startTime = $this._getTime(data.startDate);
                }

                if (data.endDate) {
                    data.endTime = $this._getTime(data.endDate);
                }
            }

            if (!data.frequency || data.frequency == '0') {
                data.frequency = '1';
            }

            if (data.objectId) {
                var rMap = $.rk.eventViewerWindow.prototype.rMap;
                $this.$entry.parent().html(['<span class="task_group"><p class="feed-group-name"><span class="feed-group-class ',
                    rMap[data.belongId].cname, '"></span><a title="' + rk.i18n('SCHEDULE_24') + '：', rMap[data.belongId].name, '" href="',
                    rMap[data.belongId].url + data.sourceEntity.id, '">', data.sourceEntity.name,
                    '</a><input type="hidden" name="belongId"/><input type="hidden" name="objectId"/></p></span>'
                ].join(''));
            } else if (opt.sourceEntity) {
                var rMap = $.rk.eventViewerWindow.prototype.rMap;
                $this.$entry.parent().html(['<span class="task_group"><p class="feed-group-name"><span class="feed-group-class ',
                    rMap[opt.entityId].cname, '"></span><a title="' + rk.i18n('SCHEDULE_24') + '：', rMap[opt.entityId].name, '" href="',
                    rMap[opt.entityId].url + opt.sourceEntity.id, '">', opt.sourceEntity.name,
                    '</a><input type="hidden" name="belongId"/><input type="hidden" name="objectId"/></p></span>'
                ].join(''));
            } else {
                if (SESSION.tenantType == 1) {
                    data.belongId = '66';
                } else {
                    data.belongId = '1';
                }
            }
            data.members = data.waitingMember.concat(data.acceptMember);
            if (data.members && data.members.length) {
                data.members = $.map(data.members, function(userid) {
                    var o = data.users[userid];
                    var currentUser = window.SESSION.user;
                    var userInfo = rk_userService.getUserInfo(o.id);
                    return {
                        //key: o.id,
                        //value: o.name,
                        value: o.id,
                        label: o.name,
                        icon: userInfo.icon,
                        pic: userInfo.icon //'/img/default_face.png'
                    };
                });
            }
            if (opt.ownerUser) {
                data.members = [];
                if (opt.ownerUser.name) {
                    opt.ownerUser.label = opt.ownerUser.name;
                }
                data.members.push(opt.ownerUser);
            }
            $elem.scheduleformbean('setAll', data);
            if (opt.eventId && SESSION.user.id != data.createdBy) {
                $elem.find('[name="members"]').closest('.schedule_field').hide();
            }
        },
        _getTime: function(date) {
            return ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2)
        },
        _changeRepeatInfo: function() {
            var $this = this,
                $elem = this.element,
                opt = this.options;

            $this.$rptinfo.find('span').remove();
            if ($this.$repeat.get(0).checked) {
                var arSpan = ['<span style="margin-left:6px;">', '</span>'];
                $this.$rptinfo.append(arSpan.join($this.$repeattype.find('option:selected').text()) + '<span>，</span>' + arSpan.join($this.$stoptype.find('option:selected').text()) +
                    ($this.$stoptype.val() == '2' ? '<span>：</span>' + arSpan.join($this.$stopcond.val()) : ''));
            }
        }
    });

    $.widget("rk.taskEditController", {
        options: {
            act: '', //create, edit, tip
            disabled: false,
            endDate: null,
            endTime: null,
            startDate: null,
            startTime: null,
            viewName: "month", //agendaDay, agendaWeek, month
            eventId: '',
            closeMe: null,
            planFinishDate: '',
            eventType: '', //task, schedule
            scheduleSucc: $.noop, //new
            scheduleFail: $.noop, //new
            taskSucc: $.noop, //new
            taskFail: $.noop //new
        },
        _create: function() {
            var $this = this,
                $elem = this.element,
                opt = this.options;

            var $named = $elem.find('[name]');
            $this.$finishDate = $named.filter('[name="finishDate"]');
            $this.$finishTime = $named.filter('[name="finishTime"]');
            $this.$reminder = $named.filter('[name="reminder"]');
            $this.$owner = $named.filter('[name="ownerId"]');
            $this.$player = $named.filter('[name="members"]');
            $this.$relation = $named.filter('[name="belongId"]');
            $this.$entry = $named.filter('[name="objectId"]');
            $this.$more = $elem.find('a.js-schedule-more');
            $this.$upload = $named.filter('[name="files"]');
            $this.$queue = $elem.find('div.uploadifyQueue').uniqueId().show().width(380);
            $this.$tooltip = $elem.find('a.js-tooltip');
            $this.$btnClose = $elem.find('a.js-close');
            $this.$btnCreate = $elem.find('a.js-create');

            $this.initUI();
            $elem.scheduleformbean();
            $this.initValue();
        },
        initUI: function() {
            var $this = this,
                $elem = this.element,
                opt = this.options;

            var effect;
            $this.$tooltip.tooltip({
                tooltipClass: 'qtip-dark-rk'
            });

            $this.$finishDate.datepicker({
                showOtherMonths: true,
                selectOtherMonths: true
            });
            $this.$finishTime.timepicker({
                showOtherMonths: true,
                selectOtherMonths: true
            });
            $this.$owner.rkUser({
                onSelect: function(userId, userName) {
                    $this.$owner.val(userName);
                    $this.$owner.attr('userid', userId);
                }
            });
            if (opt.ownerUser) {
                $this.$owner.rkUser('setUser', opt.ownerUser.id, opt.ownerUser.name);
            }
            $this.$player.snsmultipeopleselector({
                position: {
                    my: 'left top+2'
                }
            });

            $this.$entry.autocomplete({
                source: $.noop,
                minLength: 1,
                select: function(event, ui) {
                    var item = ui.item;
                    $this.$entry.val(item.label);
                    $this.$entry.attr('objectId', item.value);
                    return false;
                },
                focus: function(event, ui) {
                    var item = ui.item;
                    $this.$entry.val(item.label);
                    $this.$entry.attr('objectId', item.value);
                    return false;
                }
            });
            $this.$relation.on('change', function(evt) {
                var $option = $('option:selected', this),
                    url = $option.attr('url');
                $this.$entry.autocomplete('option', 'source', function(request, response) {
                    $.getJSON(url + '&key=' + request.term).done(function(json) {
                        var returnJson = json;
                        for (var i = 0; i < json.length; i++) {
                            if (json[i].label && json[i].value) {
                                break;
                            } else {
                                returnJson[i].label = json[i].name;
                                returnJson[i].value = json[i].id;
                            }
                        }
                        response($.map(returnJson, function(item) {
                            return {
                                label: item.label,
                                value: item.value
                            };
                        }));
                    });
                });
                evt.isTrigger || $this.$entry.val('').trigger('focus');
            }).triggerHandler('change');

            $this.$more.on('click', function(evt) {
                evt.preventDefault();
                $(this).parent().hide().nextAll().show(effect).find(':input').trigger('focus');
                $.setPopupLayersPosition();
            });
            if (opt.eventId) {
                $this.$btnCreate.text(rk.i18n('SAVE'));
                $elem.find('.fileinput-box').hide();
                $this.$more.triggerHandler('click');
            } else {
                $elem.find('.fileinput-box').multifileuploader({
                    url: '/json/global_uploadify/task-create-upload.action',
                    itemSuccess: function() {
                        $elem.find('div.schedule_pop_content').css('height', 430).beScroll({
                            theme: 'dark'
                        });
                        $elem.find('div.schedule_pop_content').beScrollTo('bottom');
                    }
                });
                /*var fileRecorder;
                $this.$upload.uniqueId().uploadSingleFile({
                    uploader: '/json/global_uploadify/task-create-upload.action',
                    queueID: $this.$queue.attr('id'),
                    buttonClass: 'file_select', // A class name to add to the browse button DOM object
                    buttonCursor: 'hand', // The cursor to use with the browse button
                    removeCompleted: false,
                    removeTimeout: 0,
                    buttonText: rk.i18n('APPS_FILE_ADD_FILE'),
                    fileTypeDesc: rk.i18n('APPS_FILE_ALL_FILE'),
                    fileTypeExts: '*.*',
                    uploadLimit: 10,
                    fileSizeLimit: '80MB',
                    fileObjName: 'uploadFile',
                    formData: {
                        pageTenantId: SESSION.tenantId
                    },
                    onSelect: function(file) {
                        if (fileRecorder) {
                            delete $this.$upload.data('uploadify').queueData.files[fileRecorder.id];
                            $this.$upload.uploadify("cancel", [fileRecorder.id], true);
                        }
                    },
                    onCancel: function(file) {
                        fileRecorder = null;
                    },
                    onUploadStart: function(file) {},
                    onUploadSuccess: function(file, data, response) {
                        data = $.parseJSON(data);
                        if (data.status == 0) {
                            fileRecorder = $.extend(data, file);
                        } else {
                            delete $this.$upload.data('uploadify').queueData.files[fileRecorder.id];
                            $this.$upload.uploadify("cancel", [fileRecorder.id], true);
                            fileRecorder = null;
                        }
                    },
                    onDialogClose: function(queueData) {}
                });*/
            }

            $this.$btnClose.on('click', function(evt) {
                evt.preventDefault();
                rk.closePopup();
            });


            $this.$btnCreate.on('click', function(evt) {
                evt.preventDefault();
                var formdata = $elem.scheduleformbean('getAll');

                if (!formdata.name) {
                    return $.msg(rk.i18n('TASK_NAME_NOT_BLANK'));
                }
                if (formdata.name.length > 30) {
                    return $.msg(rk.i18n('TASK_TEXT_12'));
                }
                if (!formdata.finishDate || !formdata.finishTime) {
                    return $.msg(rk.i18n('TASK_INPUT_END_TIME'));
                }
                if (!formdata.ownerId) {
                    return $.msg(rk.i18n('TASK_TEXT_8'));
                }
                if (formdata.description && formdata.description.length > 500) {
                    return $.msg(rk.i18n('TASK_DESCRIPTION_NOT_MORE_THAN'));
                }

                if (opt.sourceEntity) {
                    formdata.objectId = {
                        value: opt.sourceEntity.id
                    };
                    formdata.belongId = opt.entityId;
                }

                var postdata = {
                    'paramMap.taskName': formdata.name,
                    'paramMap.planFinishDate': $.datepicker.formatDate('yy-mm-dd', formdata.finishDate),
                    'paramMap.planFinishTime': formdata.finishTime || '00:00',
                    'paramMap.belongId': formdata.belongId,
                    //'paramMap.objectId': formdata.objectId ? (formdata.objectId.value || formdata.objectId) : '',
                    'paramMap.objectId': formdata.objectId ? formdata.objectId.value : '',
                    'paramMap.ownerId': formdata.ownerId ? formdata.ownerId : '',
                    'paramMap.description': formdata.description,
                    'memberIds': formdata.members ? formdata.members.join(',') : '',
                    'reminder': formdata.reminder
                };
                if (opt.eventId) {
                    postdata['paramMap.id'] = formdata.id;
                } else {
                    var $upload = $elem.find('.fileinput-box');
                    if ($upload.multifileuploader('status').uploading) {
                        return $.msg(rk.i18n('文件上传中...'));
                    }
                    var files = $upload.multifileuploader('val');

                    // var files = $elem.find('.fileinput-box').multifileuploader('val');

                    // if (!files.length) {
                    //     return $.msg(rk.i18n('APPS_FILE_CHOOSE_FILE_UPLOAD'));
                    // }

                    // var fileUploaded = true;
                    // $.each(files, function(k, v) {
                    //     if (!v.fileUrl || v.fileUrl == '') {
                    //         fileUploaded = false;
                    //     }
                    // });
                    // if (!fileUploaded) {
                    //     return $.msg(rk.i18n('文件上传中...'));
                    // }
                    postdata['attachments'] = JSON.stringify(files);
                    //postdata['attachments'] = fileRecorder ? JSON.stringify(fileRecorder) : '';
                }
                var $lnk = $(this).loading(),
                    behavior = opt.eventId ? rk.i18n('SCHEDULE_11') : rk.i18n('SCHEDULE_12');

                //if (!opt.eventId) {
                //    if(window._hmt){_hmt.push(['_trackEvent', 'operate', 'task_add', window.SESSION.tenantName]);}
                //}
                $.post('/json/crm_task/' + (opt.eventId ? 'update' : 'save') + '.action', postdata, null, 'json').done(function(json) {
                    if (json.status == '0') {
                        $.msg(behavior + rk.i18n('SUCCESS'), 1);
                        rk.closePopup();
                        $this._delay(function() {
                            opt.taskSucc(json);
                        }, 1000);
                    } else {
                        $.msg(behavior + rk.i18n('FAILED'));
                        opt.taskFail();
                        $lnk.loading('end');
                    }
                }).fail(function(def, code, message) {
                    def.status != 0 && $.msg(rk.i18n('REQUEST_ERROR'));
                    $lnk.loading('end');
                });
            });

        },
        initValue: function() {
            var $this = this,
                $elem = this.element,
                opt = this.options;
            if (opt.eventId) {
                $elem.hide();
                var $loading = $('<div class="cal-loading"><span>' + rk.i18n('LOADING') + '…</span></div>').insertAfter($elem);
                $.getJSON('/json/crm_task/detail.action?taskId=' + opt.eventId, function(json) {
                    $loading.remove();
                    $elem.show();
                    $this._initValue(json.data);
                });
            } else {
                var d = new Date();
                var data = {
                    "task": {
                        "id": "",
                        "name": "",
                        "description": "",
                        "planFinishDate": +new Date(opt.endDate.split('-').join('/') + (opt.endTime ? ' ' + opt.endTime : (' ' + d.getHours() + ':' + d.getMinutes()))),
                        "reminder": -1,
                        'ownerId': SESSION.user.id
                    },
                    "members": opt.userId && SESSION.user.id != opt.userId ? [opt.userId] : [],
                    "users": (function(o) {
                        var obj = {};
                        obj[SESSION.user.id] = $.extend({}, o);
                        if (opt.userId && SESSION.user.id != opt.userId) {
                            obj[opt.userId] = {
                                id: opt.userId,
                                name: opt.userName || '接口没给名'
                            };
                        }
                        return obj;
                    })(window.SESSION.user)
                };
                $this._initValue(data);
            }
        },
        _initValue: function(data) {
            var $this = this,
                $elem = this.element,
                opt = this.options;
            data = $.extend(true, data, data.task);
            delete data.task;

            data.isPrivate = data.isPrivate == '1';

            if (data.planFinishDate) {
                data.finishDate = new Date(Number(data.planFinishDate));
                data.finishTime = $this._getTime(data.finishDate);
            }

            if (data.objectId) {
                data.objectId = {
                    value: data.sourceEntity.id,
                    label: data.sourceEntity.name
                };
            } else if (opt.sourceEntity) {
                var rMap = $.rk.eventViewerWindow.prototype.rMap;
                $this.$entry.parent().html(['<span class="task_group"><p class="feed-group-name"><span class="feed-group-class ',
                    rMap[opt.entityId].cname, '"></span><a title="' + rk.i18n('SCHEDULE_24') + '：', rMap[opt.entityId].name, '" href="',
                    rMap[opt.entityId].url + opt.sourceEntity.id, '">', opt.sourceEntity.name,
                    '</a><input type="hidden" name="belongId"/><input type="hidden" name="objectId"/></p></span>'
                ].join(''));
            } else {
                if (SESSION.tenantType == 1) {
                    data.belongId = '66';
                } else {
                    data.belongId = '1';
                }
            }

            if (data.ownerId) {
                data.ownerId = $.map([data.ownerId], function(userid) {
                    var o = data.users[userid];
                    return {
                        key: o.id,
                        value: o.name
                    };
                });
            }

            if (data.members && data.members.length) {
                data.members = $.map(data.members, function(userid) {
                    var o = data.users[userid];
                    var currentUser = window.SESSION.user;
                    var userInfo = rk_userService.getUserInfo(o.id);
                    return {
                        //key: o.id,
                        //value: o.name,
                        value: o.id,
                        label: o.name,
                        icon: userInfo.icon //'/img/default_face.png'
                    };
                });
            }
            $elem.scheduleformbean('setAll', data);
        },
        _getTime: function(date) {
            return ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2)
        }
    });

    //事件查看tip
    $.widget('rk.eventViewerWindow', $.extend(true, {}, $.superClass.tipApi, {
        options: {
            event: null
        },
        _create: function() {
            var $this = this,
                $elem = this.element,
                opt = this.options;
            opt.eventId = opt.event.id
            opt.eventType = opt.event.planFinishDate ? 'task' : 'schedule';
            $elem.on('click', function(evt) {
                if (!$elem.hasClass('ui-draggable-dragging') && !$elem.hasClass('ui-resizable-resizing')) {
                    $this.loadDetail();
                }
            });
        },
        loadDetail: function() {
            var $this = this,
                $elem = this.element,
                opt = this.options;
            var date = opt.event.start._d;
            var dateString = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
            $.getJSON('/json/crm_' + opt.eventType + '/detail.action?' + opt.eventType + 'Id=' + opt.eventId + "&queryDate=" + dateString, function(json) {
                if (json.status == '0') {
                    if (json.data.schedule && json.data.schedule.isPrivate == '1' && !json.data.schedule.accessible) {
                        $this.showLimit(json.data);
                    } else {
                        $this[opt.eventType == 'schedule' ? 'showSchedule' : 'showTask'](json.data);
                    }
                    $this.$tipContent.on('click', function(evt) {
                        evt.stopPropagation();
                    });
                    var at = $elem.height() > 60 ? 'center center' : 'top left';
                    $elem.qtip({
                            content: {
                                text: $this.$tipContent,
                                title: {
                                    button: false
                                }
                            },
                            position: {
                                my: 'bottom left',
                                at: at,
                                viewport: true
                            },
                            show: {
                                event: 'click',
                                solo: true,
                                ready: true
                            },
                            hide: {
                                target: $(document), // Defaults to target element
                                event: 'click', // Hide on mouse out by default
                                effect: true, // Use default 90ms fade effect
                                delay: 0, // No hide delay by default
                                fixed: false, // Non-hoverable by default
                                inactive: false, // Do not hide when inactive
                                leave: 'window', // Hide when we leave the window
                                distance: false // Don't hide after a set distance
                            },
                            style: {
                                classes: 'qtip-shadow qtip-light ui-front'
                            },
                            events: {
                                visible: function() {
                                    var descObj = $this.$tipContent.find('div.js-description');
                                    var title = descObj.attr('title')
                                        //该处改动的目的：rk.ellipsis方法中，当title含有连续多个\n\n（双换行）时，while循环不会结束，并引起浏览器崩溃，此处代码用来消掉多余的双换行。
                                    if (title) {
                                        while (title.indexOf('\n\n') >= 0) {
                                            title = title.replace(/\n\n/g, "\n"); //多个换行替换成一个
                                        }
                                        descObj.attr('title', title);
                                        descObj.ellipsis();
                                    }
                                }
                            }
                        }) //.qtip('show')

                } else {
                    $.msg(rk.i18n('REQUEST_ERROR'))
                }
            });
        },
        showLimit: function(data) {
            var $this = this,
                $elem = this.element,
                opt = this.options;

            data.between = (function(o) {
                return $.map([$.datepicker.formatDate('yy-mm-dd', new Date(+o.startDate)), o.isAllDay == '1' ? '' : $this._getTime(new Date(+o.startDate)), '到', $.datepicker.formatDate('yy-mm-dd', new Date(+o.endDate)), o.isAllDay == '1' ? '' : $this._getTime(new Date(+o.endDate))], function(str) {
                    return str ? '<span>' + str + '</span>' : null;
                }).join('');
            })(data.schedule);

            //template.config('escape', false);
            var html = require('oa/tmpl/schedule/editor/template_calScheduleLimit.tpl'); //template('template_calScheduleLimit', data);
            html = rk.templateText(html, data);
            // $elem.html(html);
            $this.$tipContent = $(html);

        },
        rMap: {
            1: {
                name: SESSION.keywords.account,
                url: '/final/account.action?id=',
                cname: 'account'
            },
            3: {
                name: SESSION.keywords.opportunity,
                url: '/final/opportunity.action?id=',
                cname: 'opportunity'
            },
            2: {
                name: SESSION.keywords.contract,
                url: '/final/contact.action?id=',
                cname: 'contact'
            },
            6: {
                name: SESSION.keywords.campaign,
                url: '/final/campaign.action?id=',
                cname: 'campaign'
            },
            11: {
                name: SESSION.keywords.lead,
                url: '/final/lead.action?id=',
                cname: 'leads'
            },
            66: {
                name: SESSION.keywords.agent,
                url: '/final/agent.action?id=',
                cname: 'terminal'
            },
            67: {
                name: SESSION.keywords.terminal,
                url: '/final/terminal.action?id=',
                cname: 'terminal'
            }
        },
        showSchedule: function(data) {
            var $this = this,
                $elem = this.element,
                opt = this.options;
            if (data.schedule.colorType.dummyType == 32) { //巡访计划
                $this.showVisitPlan(data);
                return;
            }

            data.isPrivate = data.schedule.isPrivate == '1' ? '<span class="lock"></span>' : '';
            // data.name = '<a href="javascript:;">' + data.schedule.name + '</a>';
            data.id = data.schedule.id;
            data.name = data.schedule.name;

            data.buttons = (function(o) {
                var arButtons = [],
                    allMembers = o.acceptMember;
                if (+SESSION.user.id == o.schedule.createdBy || ~$.inArray(+SESSION.user.id, allMembers)) {
                    arButtons.push('<a href="javascript:;" act="edit">' + rk.i18n('EDIT') + '</a>');
                }
                if (+SESSION.user.id == o.schedule.createdBy) {
                    arButtons.push('<a href="javascript:;" act="dele" schedulename="' + o.name + '">' + rk.i18n('DELETE') + '</a>');
                } else if (~$.inArray(+SESSION.user.id, allMembers)) {
                    arButtons.push('<a href="javascript:;" act="quit" schedulename="' + o.name + '">' + rk.i18n('SCHEDULE_57') + '</a>');
                }
                if (o.schedule.isPrivate == '0' || o.schedule.accessible == '1') {
                    //arButtons.push('<a target="_blank" href="/final/schedule.action?scheduleId=' + o.schedule.id + '">查看详情</a>');
                    arButtons.push('<a target="_blank" href="/final/schedule.action?scheduleId=' + o.schedule.id + '">' + rk.i18n('SCHEDULE_56') + '</a>');
                }
                return arButtons.length ? ['<div class="schedule_footer edit_schedule_footer"><div class="schedule_button_area">', arButtons.join('<span>|</span>'), '</div></div>'].join('') : '';
            })(data);

            data.between = (function(o) {
                return $.map([$.datepicker.formatDate('yy-mm-dd', new Date(+o.startDate)), o.isAllDay == '1' ? '' : $this._getTime(new Date(+o.startDate)), rk.i18n('TO'), $.datepicker.formatDate('yy-mm-dd', new Date(+o.endDate)), o.isAllDay == '1' ? '' : $this._getTime(new Date(+o.endDate))], function(str) {
                    return str ? '<span>' + str + '</span>' : null;
                }).join('');
            })(data.schedule);

            data.rptinfo = (function(o) {
                if (o.isRecur == '1') {
                    return '<div class="schedule_field relation_field"><div class="field_name"></div><div class="field_content"><div class="tixin">' +
                        $.map([
                            ['', rk.i18n('SCHEDULE_25'), rk.i18n('SCHEDULE_26'), rk.i18n('SCHEDULE_27')][o.frequency], rk.i18n('SCHEDULE_REPEAT'), ',',
                            o.recurStopCondition == '1' ? rk.i18n('SCHEDULE_NO_END') : (rk.i18n('SCHEDULE_54') + $.datepicker.formatDate('yy-mm-dd', new Date(+o.recurStopValue)) + rk.i18n('SCHEDULE_55'))
                        ], function(str) {
                            return str ? '<span>' + str + '</span>' : null;
                        }).join('') + '</div></div></div>';
                } else {
                    return '';
                }
            })(data.schedule);

            data.remind = {
                '-1': rk.i18n('SCHEDULE_NO_REMIND'),
                '0': rk.i18n('SCHEDULE_IN_TIME'),
                '600': rk.i18n('SCHEDULE_EARLY_10MINUTE'),
                '1800': rk.i18n('SCHEDULE_EARLY_30MINUTE'),
                '3600': rk.i18n('SCHEDULE_EARLY_1HOUR'),
                '7200': rk.i18n('SCHEDULE_EARLY_2HOUR'),
                '21600': rk.i18n('SCHEDULE_EARLY_6HOUR'),
                '86400': rk.i18n('SCHEDULE_EARLY_1DAY'),
                '54000': rk.i18n('SCHEDULE_9_INDAY'),
                '-32400': rk.i18n('SCHEDULE_9_BEFOREDAY')
            }[data.schedule.reminder];

            data.acceptMember = $.map(data.acceptMember, function(uid) {
                return '<li><a href="/final/user.action?uid=' + uid + '" title="' + data.users[uid].name + '"><img src="' + (data.users[uid].icon || DEFAULTS.USER_DEFAULT_ICON) + '"/></a></li>';
            }).join('');
            if (data.acceptMember) {
                data.members = '<ul class="task_people_list">' + data.acceptMember + '</ul>';
            }
            data.waitingMember = $.map(data.waitingMember || [], function(uid) {
                return '<li><a href="/final/user.action?uid=' + uid + '" title="' + data.users[uid].name + '"><img src="' + (data.users[uid].icon || DEFAULTS.USER_DEFAULT_ICON) + '"/></a></li>';
            }).join('');
            if (data.waitingMember) {
                data.waiting = '<div class="confirmed_people participants"><span class="tip">' + rk.i18n('SCHEDULE_28') + '</span><ul class="task_people_list">' + data.waitingMember + '</ul></div>';
            }
            data.rejectMember = $.map(data.rejectMember || [], function(uid) {
                return '<li><a href="/final/user.action?uid=' + uid + '" title="' + data.users[uid].name + '"><img src="' + (data.users[uid].icon || DEFAULTS.USER_DEFAULT_ICON) + '"/></a></li>';
            }).join('');
            if (data.rejectMember) {
                data.reject = '<div class="confirmed_people participants"><span class="tip">' + rk.i18n('SCHEDULE_29') + '</span><ul class="task_people_list">' + data.rejectMember + '</ul></div>';
            }

            if (data.schedule.objectId) {
                data.relation = (function(o) {
                    var entry = data.sourceEntity;
                    return ['<div class="schedule_field relation_field"><div class="field_name">' + rk.i18n('SCHEDULE_RELATE_BUSINESS') + '</div><div class="field_content"><div class="show_ralation_bussiness"><span class="task_group"><p class="feed-group-name"><span class="feed-group-class ', $this.rMap[o.belongId].cname, '"></span><a title="' + rk.i18n('SCHEDULE_24') + '：', $this.rMap[o.belongId].name, '" href="', $this.rMap[o.belongId].url + entry.id, '">', entry.name, '</a></p></span></div></div></div>'].join('');
                })(data.schedule);
            }

            if (data.schedule.description) {
                data.description = (function(o) {
                    var desc = o.description.split('\n');
                    desc = desc.length > 400 ? desc.slice(0, 4).join('\n') + '…' : o.description;
                    return ['<div class="schedule_field relation_field"><div class="field_name">' + rk.i18n('SCHEDULE_DESCRIPTION') + '</div><div class="field_content"><div class="remarks_des js-description" title="', $.htmlEncode(o.description), '">', $.htmlEncode(desc).replace(/\n/g, '<br>'), '</div></div></div>'].join('');
                })(data.schedule);
            }

            //template.config('escape', false);
            var html = require('oa/tmpl/schedule/editor/template_calScheduleViewer.tpl'); //template('template_calScheduleViewer', data);
            html = rk.templateText(html, data);
            // $elem.html(html);

            $this.$tipContent = $(html);

            $this.$tipContent.find('a[act="edit"]').on('click', function(evt) {
                evt.preventDefault();
                $elem.qtip('hide');
                scheduleUtil.popupEditor($.extend({}, opt, {
                    act: 'edit',
                    eventType: 'schedule'
                }));
            });
            $this.$tipContent.find('a[act="quit"]').on('click', function(evt) {
                evt.preventDefault();
                var sname = $(this).attr('schedulename');
                rk.confirm(rk.i18n('SCHEDULE_41', sname), function() {
                    $.post('/json/crm_schedule/quit.action', {
                        scheduleId: opt.eventId
                    }, null, 'json').done(function(json) {
                        if (json.status == 0) {
                            $.msg(rk.i18n('SCHEDULE_42'), 1);
                            $elem.qtip('hide');
                            scheduleUtil.loadEvents();
                        } else {
                            $.msg(rk.i18n('SCHEDULE_43'));
                        }
                    });
                });
            });
            $this.$tipContent.find('a[act="dele"]').on('click', function(evt) {
                evt.preventDefault();
                var sname = $(this).attr('schedulename');
                rk.confirm(rk.i18n('SCHEDULE_38', sname), function() {
                    $.post('/json/crm_schedule/delete.action', {
                        scheduleId: opt.eventId
                    }, null, 'json').done(function(json) {
                        if (json.status == 0) {
                            $.msg(rk.i18n('TASK_DELETE_SUCCESS'), 1);
                            $elem.qtip('hide');
                            scheduleUtil.loadEvents();
                        } else {
                            $.msg(rk.i18n('TASK_DELETE_ERROR'));
                        }
                    });
                });
            });

        },
        showVisitPlan: function(data) {
            var $this = this,
                $elem = this.element,
                opt = this.options;

            data.isPrivate = data.schedule.isPrivate == '1' ? '<span class="lock"></span>' : '';
            // data.name = '<a href="javascript:;">' + data.schedule.name + '</a>';
            data.id = data.schedule.id;
            //data.name = data.schedule.name;
            data.name = "拜访:" + data.schedule.from.name;
            if (data.users[data.schedule.createdBy]) {
                var createUser = data.users[data.schedule.createdBy];
                data.createTimeOrUser = "该拜访计划于 " + moment(data.schedule.createdAt - 0).format("YYYY-MM-DD HH:mm") + "" + " 由 <a target='_blank' href='/final/user.action?uid=" + createUser.id + "'>" + $.htmlEncode(createUser.name) + "</a> 创建";
            }

            data.buttons = (function(o) {
                var arButtons = [],
                    allMembers = o.acceptMember;
                var visit_result_button = "";
                if (o.schedule.finishStatus == 1) {
                    if (o.schedule.isPrivate == '0' || o.schedule.accessible == '1') {
                        var date = opt.event.start._d;
                        visit_result_button = '<span class="schedule_visit_record"><a href="/final/visit.action?id=' + data.schedule.visitRecord.id + '" target="_blank" recordId="' + data.schedule.visitRecord.id + '" date="' + date + '" visitId="' + data.schedule.id + '" act="visit_result">查看拜访结果</a></span>'; //链接到巡访记录
                        data.finishStatus = 1;
                    }
                } else {
                    var date = opt.event.start._d;
                    var dateString = moment(date.getTime()).format("YYYY-MM-DD");
                    var nowDate = new Date();
                    var nowDateString = moment(nowDate.getTime()).format("YYYY-MM-DD");
                    if (dateString >= nowDateString) {
                        if (+SESSION.user.id == o.schedule.createdBy) {
                            arButtons.push('<a href="javascript:;" act="edit">编辑</a>');
                        }
                        if (+SESSION.user.id == o.schedule.createdBy) {
                            arButtons.push('<a href="javascript:;" act="dele" schedulename="' + o.name + '">' + rk.i18n('DELETE') + '</a>');
                        }
                    } else {
                        data.finishStatus = 0;
                    }
                }
                /*if (o.schedule.isPrivate == '0' || o.schedule.accessible == '1') {
                    //arButtons.push('<a target="_blank" href="/final/schedule.action?scheduleId=' + o.schedule.id + '">查看详情</a>');
                    arButtons.push('<a target="_blank" href="/final/schedule.action?scheduleId=' + o.schedule.id + '">查看计划详情</a>');
                }*/
                return arButtons.length != 0 || visit_result_button ? ['<div class="schedule_footer edit_schedule_footer">' + visit_result_button + '<div class="schedule_button_area">', arButtons.join('<span>|</span>'), '</div></div>'].join('') : '';
            })(data);

            data.between = (function(o) {
                if (o.frequency == 0) {
                    return $.map([$.datepicker.formatDate('yy-mm-dd', new Date(+o.startDate)), o.isAllDay == '1' ? '' : $this._getTime(new Date(+o.startDate)), '到', $.datepicker.formatDate('yy-mm-dd', new Date(+o.endDate)), o.isAllDay == '1' ? '' : $this._getTime(new Date(+o.endDate))], function(str) {
                        return str ? '<span>' + str + '</span>' : null;
                    }).join('');
                } else {
                    return $.map([$.datepicker.formatDate('yy-mm-dd', new Date(+o.startDate)), o.isAllDay == '1' ? '' : $this._getTime(new Date(+o.startDate)), '到', $.datepicker.formatDate('yy-mm-dd', new Date(+o.recurStopValue)), o.isAllDay == '1' ? '' : $this._getTime(new Date(+o.recurStopValue))], function(str) {
                        return str ? '<span>' + str + '</span>' : null;
                    }).join('');
                }
            })(data.schedule);

            data.rptinfo = (function(o) {
                if (o.isRecur == '1') {
                    var recurString = $.map([
                        ['', '每日', '每周', '每月'][o.frequency], '重复', ',',
                        o.recurStopCondition == '1' ? rk.i18n('SCHEDULE_NO_END') : ('到' + $.datepicker.formatDate('yy-mm-dd', new Date(+o.recurStopValue)) + '结束')
                    ], function(str) {
                        return str ? '<span>' + str + '</span>' : null;
                    }).join('');
                    if (data.schedule.rules) {
                        var rules = data.schedule.rules
                        if (o.frequency == 2) {
                            var week_days = rules.split(',');
                            var week_days_json = {
                                "1": "周一",
                                "2": "周二",
                                "3": "周三",
                                "4": "周四",
                                "5": "周五",
                                "6": "周六",
                                "7": "周日"
                            };
                            var endString = '';
                            for (var i = 0; i < week_days.length; i++) {
                                endString += week_days_json[week_days[i]];
                                if (i != week_days.length - 1) {
                                    endString += ',';
                                }
                            }
                            recurString = "计划将于每" + endString + "重复"; //+' 到' + $.datepicker.formatDate('yy-mm-dd', new Date(+o.recurStopValue)) + '结束';
                            data.frequencyName = "按周重复";
                        } else if (o.frequency == 3) {
                            recurString = "计划将于每月" + rules + "重复";
                            data.frequencyName = "按月重复";
                        }

                    }
                    return '<div class="schedule_field relation_field"><div class="field_name"></div><div class="field_content"><div class="tixin">' +
                        recurString + '</div></div></div>';
                } else {
                    return '';
                }
            })(data.schedule);

            /*data.remind = {
                '-1': '不提醒',
                '0': '准时',
                '600': '提前10分钟',
                '1800': '提前30分钟',
                '3600': '提前1小时',
                '7200': '提前2小时',
                '21600': '提前6小时',
                '86400': '提前1天',
                '54000': '1天前（上午9点）',
                '-32400': '当天（上午9点）'
            }[data.schedule.reminder];*/

            data.acceptMember = $.map(data.acceptMember, function(uid) {
                return '<li><a target="_blank" href="/final/user.action?uid=' + uid + '" title="' + data.users[uid].name + '"><img src="' + (data.users[uid].icon || DEFAULTS.USER_DEFAULT_ICON) + '"/></a></li>';
            }).join('');
            if (data.acceptMember) {
                data.members = '<ul class="task_people_list">' + data.acceptMember + '</ul>';
            }
            /*data.waitingMember = $.map(data.waitingMember || [], function(uid) {
                return '<li><a href="/final/user.action?uid=' + uid + '" title="' + data.users[uid].name + '"><img src="' + (data.users[uid].icon || DEFAULTS.USER_DEFAULT_ICON) + '"/></a></li>';
            }).join('');
            if (data.waitingMember) {
                data.waiting = '<div class="confirmed_people participants"><span class="tip">待确认</span><ul class="task_people_list">' + data.waitingMember + '</ul></div>';
            }
            data.rejectMember = $.map(data.rejectMember || [], function(uid) {
                return '<li><a href="/final/user.action?uid=' + uid + '" title="' + data.users[uid].name + '"><img src="' + (data.users[uid].icon || DEFAULTS.USER_DEFAULT_ICON) + '"/></a></li>';
            }).join('');
            if (data.rejectMember) {
                data.reject = '<div class="confirmed_people participants"><span class="tip">被拒绝</span><ul class="task_people_list">' + data.rejectMember + '</ul></div>';
            }*/

            /*if (data.schedule.objectId) {
                data.relation = (function (o) {
                    var entry = data.sourceEntity;
                    return ['<div class="schedule_field relation_field"><div class="field_name">关联业务</div><div class="field_content"><div class="show_ralation_bussiness"><span class="task_group"><p class="group_name"><span class="group_class ', $this.rMap[o.belongId].cname, '"></span><a title="'+rk.i18n('SCHEDULE_24') + '：', $this.rMap[o.belongId].name, '" href="', $this.rMap[o.belongId].url + entry.id, '">', entry.name, '</a></p></span></div></div></div>'].join('');
                })(data.schedule);
            }*/

            /*if (data.schedule.description) {
                data.description = (function(o) {
                    var desc = o.description.split('\n');
                    desc = desc.length > 400 ? desc.slice(0, 4).join('\n') + '…' : o.description;
                    return ['<div class="schedule_field relation_field"><div class="field_name">备注</div><div class="field_content"><div class="remarks_des js-description" title="', o.description, '">', desc.replace(/\n/g, '<br>'), '</div></div></div>'].join('');
                })(data.schedule);
            }*/

            //template.config('escape', false);
            var html = require('oa/tmpl/schedule/editor/template_calVisitPlanViewer.tpl'); //template('template_calScheduleViewer', data);
            html = rk.templateText(html, data);
            // $elem.html(html);

            $this.$tipContent = $(html);

            $this.$tipContent.find('a[act="edit"]').on('click', function(evt) {
                evt.preventDefault();
                $elem.qtip('hide');
                /*scheduleUtil.popupEditor($.extend({}, opt, {
                    act: 'edit',
                    eventType: 'schedule'
                }));*/
                rk.dialog({
                    title: '编辑拜访计划',
                    //width:"930",
                    success: function(contentElem) {
                        var date = opt.event.start._d;
                        var dateString = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
                        require.async(["../../visit/visitPlanUpdateDialogCtrl"], function() {
                            contentElem.visitPlanUpdateDialogCtrl({
                                param: {
                                    planId: opt.eventId,
                                    changeDate: dateString
                                }
                            }); //初始化弹框内容的Ctrl
                        });
                    },
                    footer: ['cancel', {
                        act: 'ok',
                        visible: true,
                        text: '保存'
                    }]
                });
            });
            $this.$tipContent.find('a[act="dele"]').on('click', function(evt) {
                evt.preventDefault();
                var sname = $(this).attr('schedulename');
                var date = opt.event.start._d;
                var dateString = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
                var confirmString = "";
                if (data.schedule.frequency == 0) {
                    confirmString = "拜访计划将删除";
                }
                if (data.schedule.frequency == 2 || data.schedule.frequency == 3) {
                    confirmString = "拜访计划将自今天截止";
                }
                rk.confirm('删除拜访计划【' + sname + '】后，' + confirmString, function() {
                    $.post('/json/crm_visitPlan/delete-visit-plan-for-future.action', {
                        planId: opt.eventId
                            //changeDate: dateString
                    }, null, 'json').done(function(json) {
                        if (json.status == 0) {
                            $.msg(rk.i18n('TASK_DELETE_SUCCESS'), 1);
                            $elem.qtip('hide');
                            scheduleUtil.loadEvents();
                        } else {
                            $.msg(rk.i18n('TASK_DELETE_ERROR'));
                        }
                    });
                });
            });
        },
        showTask: function(data) {
            var $this = this,
                $elem = this.element,
                opt = this.options;

            data.buttons = (function(o) {
                var arButtons = [];
                if (+SESSION.user.id == o.task.createdBy || +SESSION.user.id == o.task.ownerId) {
                    arButtons.push('<a href="javascript:;" act="dele" taskname="' + o.task.name + '">' + rk.i18n('DELETE') + '</a>');
                } else if (~$.inArray(+SESSION.user.id, o.members)) {
                    arButtons.push('<a href="javascript:;" act="quit" taskname="' + o.task.name + '">' + rk.i18n('SCHEDULE_57') + '</a>');
                }
                arButtons.push('<a target="_blank" href="/final/task.action?taskId=' + o.task.id + '">' + rk.i18n('SCHEDULE_56') + '</a>');
                return arButtons.join('<span>|</span>');
            })(data);
            data.isDisable = +SESSION.user.id == data.task.createdBy || +SESSION.user.id == data.task.ownerId ? '' : 'task_tickbox_disabled';
            data.status = data.task.status == '2' ? 'done' : 'normal';
            var pfd = new Date(+data.task.planFinishDate);
            data.planFinishDate = $.datepicker.formatDate('yy-mm-dd', pfd) + ' ' + ('0' + pfd.getHours()).slice(-2) + ':' + ('0' + pfd.getMinutes()).slice(-2);
            data.remind = {
                '-1': rk.i18n('TASK_REMIND_NO'),
                '0': rk.i18n('TASK_REMIND_ON_TIME'),
                '300': rk.i18n('TASK_REMIND_BEFORE_300'),
                '600': rk.i18n('TASK_REMIND_BEFORE_600'),
                '1800': rk.i18n('TASK_REMIND_BEFORE_1800'),
                '3600': rk.i18n('TASK_REMIND_BEFORE_3600'),
                '7200': rk.i18n('TASK_REMIND_BEFORE_7200'),
                '21600': rk.i18n('TASK_REMIND_BEFORE_21600'),
                '86400': rk.i18n('TASK_REMIND_BEFORE_86400'),
                '172800': rk.i18n('TASK_REMIND_BEFORE_172800')
            }[data.task.reminder];

            data.owner = '<ul class="task_people_list"><li><a href="javascript:;" title="' + data.users[data.task.ownerId].name + '"><img src="' + (data.users[data.task.ownerId].icon || DEFAULTS.USER_DEFAULT_ICON) + '"/></a></li></ul>';

            data.members = $.map(data.members, function(uid) {
                return '<li><a href="javascript:;" title="' + data.users[uid].name + '"><img src="' + (data.users[uid].icon || DEFAULTS.USER_DEFAULT_ICON) + '"/></a></li>';
            }).join('');
            if (data.members) {
                data.members = '<div class="schedule_field relation_field"><div class="field_name">' + rk.i18n('SCHEDULE_PARTNER') + '</div><div class="field_content"><div class="participants"><ul class="task_people_list">' + data.members + '</ul></div></div></div>';
            }

            if (data.task.objectId) {
                data.relation = (function(o) {
                    var entry = data.sourceEntity;
                    return ['<div class="schedule_field relation_field"><div class="field_name">' + rk.i18n('SCHEDULE_RELATE_BUSINESS') + '</div><div class="field_content"><div class="show_ralation_bussiness"><span class="task_group"><p class="feed-group-name"><span class="feed-group-class ', $this.rMap[o.belongId].cname, '"></span><a title="' + rk.i18n('SCHEDULE_24') + '：', $this.rMap[o.belongId].name, '" href="', $this.rMap[o.belongId].url + entry.id, '">', entry.name, '</a></p></span></div></div></div>'].join('');
                })(data.task);
            }

            if (data.task.description) {
                data.description = (function(o) {
                    var desc = o.description.split('\n');
                    desc = desc.length > 4 ? desc.slice(0, 4).join('\n') + '…' : o.description;
                    return ['<div class="schedule_field relation_field"><div class="field_name">' + rk.i18n('SCHEDULE_DETAIL_DES') + '</div><div class="field_content"><div class="remarks_des js-description" title="', $.htmlEncode(o.description), '">', $.htmlEncode(desc).replace(/\n/g, '<br>'), '</div></div></div>'].join('');
                })(data.task);
            }

            //template.config('escape', false);
            var html = require('oa/tmpl/schedule/editor/template_calTaskViewer.tpl'); //template('template_calTaskViewer', data);
            html = rk.templateText(html, data);
            // $elem.html(html);
            $this.$tipContent = $(html);

            $this.$tipContent.find('a[act="edit"]').on('click', function(evt) {
                evt.preventDefault();
                $elem.qtip('hide');
                scheduleUtil.popupEditor($.extend({}, opt, {
                    act: 'edit',
                    eventType: 'task'
                }));
            });
            $this.$tipContent.find('a[act="quit"]').on('click', function(evt) {
                evt.preventDefault();
                var sname = $(this).attr('taskname');
                rk.confirm(rk.i18n('TASK_TEXT_20', sname), function() {
                    $.post('/json/crm_task/quit.action', {
                        taskId: opt.eventId
                    }, null, 'json').done(function(json) {
                        if (json.status == 0) {
                            $.msg(rk.i18n('SCHEDULE_42'), 1);
                            $elem.qtip('hide');
                            scheduleUtil.loadEvents();
                        } else {
                            $.msg(rk.i18n('SCHEDULE_43'));
                        }
                    });
                });
            });
            $this.$tipContent.find('a[act="dele"]').on('click', function(evt) {
                evt.preventDefault();
                var sname = $(this).attr('taskname');
                rk.confirm(rk.i18n('TASK_TEXT_21', sname), function() {
                    $.post('/json/crm_task/delete.action', {
                        taskId: opt.eventId
                    }, null, 'json').done(function(json) {
                        if (json.status == 0) {
                            $.msg(rk.i18n('TASK_DELETE_SUCCESS'), 1);
                            $elem.qtip('hide');
                            scheduleUtil.loadEvents();
                        } else {
                            $.msg(rk.i18n('TASK_DELETE_ERROR'));
                        }
                    });
                });
            });

            //修改任务状态
            $this.$tipContent.find('div.task_tickbox:not(.task_tickbox_disabled) a.js-status').on('click', function(evt) {
                evt.preventDefault();
                var $el = $(this),
                    checked = $el.hasClass('done'),
                    taskid = $el.attr('taskid');
                $.post('/json/crm_task/change-status.action', {
                    taskId: taskid,
                    taskStatus: checked ? 1 : 2
                }, null, 'json').done(function(json) {
                    if (json.status == 0) {
                        if (checked) {
                            $el.removeClass('done').addClass('normal').attr('title', rk.i18n('TASK_CLICK_FINISHED'));
                        } else {
                            $el.removeClass('normal').addClass('done').attr('title', rk.i18n('TASK_CLICK_CANCEL_FINISHED'));
                        }
                        $elem.qtip('hide');
                        scheduleUtil.loadEvents();
                    } else {
                        $.msg(rk.i18n('TASK_CHANGE_STATUS_ERROR'));
                    }
                }).fail(function(def, code, message) {
                    def.status != 0 && $.msg(rk.i18n('REQUEST_ERROR'));
                });
            });

        },
        _getTime: function(date) {
            return ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2)
        }
    }));


    $.widget('rk.scheduleformbean', $.rk.formbean, {
        get: function(name) {
            var $this = this,
                $elem = this.element,
                opt = this.options;
            if ($this._has(name)) {
                return $this._super(name);
            }
        },
        set: function(name, val) {
            var $this = this,
                $elem = this.element,
                opt = this.options;
            if ($this._has(name)) {
                $this._super(name, val);
            }
        }
    });
    $.widget('rk.ellipsis', {
        options: {},
        _create: function() {
            var $this = this,
                $elem = this.element,
                opt = this.options;
            var style = {
                    overflow: $elem.css('overflow'),
                    width: $elem.width(),
                    height: $elem.height()
                },
                html = $elem.attr('title');
            $elem.css('overflow', 'hidden');
            var ch = $elem.prop('offsetHeight'),
                sh = $elem.prop('scrollHeight');
            if (ch < sh) {
                while (ch < sh) {
                    html = html.slice(0, Math.ceil(html.length * ch / sh));
                    $elem.html(html.replace(/\n/g, '<br>'));
                    ch = $elem.prop('offsetHeight'), sh = $elem.prop('scrollHeight');
                }
                html = $.trim(html).replace(/[\S\s]{3}$/, '...');
                $elem.html(html.replace(/\n/g, '<br>'));
            } else {
                $elem.css(style);
            }
        }
    });

    return $;
});
